<script lang="ts" setup>
import { reactive,ref, computed } from 'vue'
import type { ElTable } from "element-plus";
import { ElMessage } from 'element-plus'
interface  RecruitmentItem{
  id: number;
  status: string;
  post: string;
  section: string;
  requirement: string;
  numberPeople: string;
  candidate: string;
  entry: string;
  time: string;
}

const currentPage = ref(1)
const pageSize = ref(10)

/**
 * 招聘岗位数据列表
 *
 * @description 存储当前页面显示的招聘信息数据，使用 reactive 包装以实现响应式更新。
 *              每条记录包括序号、状态、岗位名称、招聘部门等字段信息。
 */
const tableData = reactive([
  { id: 1, status: '进行中', post: '销售经理', section: '销售部', requirement: '纳新30人', numberPeople: 30, candidate: 0, entry: 0, time: '2023-12-09',},
  { id: 2, status: '进行中', post: '财务主管', section: '财务部', requirement: '纳新3人', numberPeople: 3, candidate: 0, entry: 0, time: '2023-12-09',},
  { id: 3, status: '进行中', post: '软件工程师', section: '技术部', requirement: '纳新16人', numberPeople: 16, candidate: 0, entry: 0, time: '2023-12-09',},
  { id: 4, status: '进行中', post: '助理', section: '人力资源中心', requirement: '纳新8人', numberPeople: 8, candidate: 0, entry: 0, time: '2023-05-09',},
])
const  multipleTableRef = ref<InstanceType<typeof ElTable>>()
const selectionItems = ref<RecruitmentItem[]>([])
const handleSelectionChange = (val: RecruitmentItem[]) => {
  selectionItems.value = val
}
const handleBatchDelete= () => {
  if (selectionItems.value.length === 0){
    ElMessage.warning('请至少选择一行');
    return
  }
  const idsToDelete = selectionItems.value.map(item => item.id);

  const idsSet = new Set(idsToDelete);
  const  indexToRemove : number[] = [];
  tableData.forEach((item, index) => {
    if (idsSet.has(item.id)) {
      indexToRemove.push(index);
    }
  })
  indexToRemove.forEach(index =>{
    tableData.splice(index, 1);
  })
  multipleTableRef.value?.clearSelection()
}
const  handleEndRecruitment = () => {
 if (selectionItems.value.length === 0){
   ElMessage.warning('请至少选择一行');
   return
 }
 selectionItems.value.forEach(item => {
   const  targetItem = tableData.find(dataItem => dataItem.id === item.id);
   if (targetItem){
     targetItem.status = '已结束';
   }
 });
 multipleTableRef.value?.clearSelection()
  ElMessage.success('操作成功')
}
const filterTableData = computed(() => {
  return tableData.filter(item => {
    const postMatch = !searchForm.post || item.post.includes(searchForm.post);
    const sectionMatch = !searchForm.section || item.section.includes(searchForm.section);
    const statusMatch = !searchForm.status || item.status.includes(searchForm.status);
    let timeMatch = true;
    if (searchForm.time) {
      // 如果选择了日期，则比较年月日部分
      const selectedDate = new Date(searchForm.time).toDateString();
      const itemDate = new Date(item.time).toDateString();
      timeMatch = selectedDate === itemDate;
    }
    return postMatch && sectionMatch && statusMatch  && timeMatch;
  })
   // 这里可以根据搜索条件过滤数据
  // 目前返回全部数据
  //return tableData
})
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}
function handleCurrentChange(val) {
  currentPage.value = val
}
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  //const end = start + pageSize.value
  //return filterTableData.value.slice(start, end)
  return filterTableData.value.slice(start, start +pageSize.value)
})
const handleAdd = () => {
  isEditing.value = false
  resetForm()
  dialogVisible.value = true
   // 可以在这里实现具体的新增逻辑
  // 例如：打开模态框、跳转到新增页面等
  //ElMessage.success('添加成功')
}
// 添加表单数据和弹窗控制变量
const dialogVisible = ref(false)
const isEditing = ref(false)
const formData = reactive({
  id: 0,
  status: '进行中',
  post: '',
  section: '',
  requirement: '',
  numberPeople: 0,
  candidate: 0,
  entry: 0,
  time: ''
})

// 重置表单方法
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    status: '进行中',
    post: '',
    section: '',
    requirement: '',
    numberPeople: 0,
    candidate: 0,
    entry: 0,
    time: ''
  })
}

// 处理保存方法
const handleSave = () => {
  if (!formData.post || !formData.section || !formData.requirement || !formData.numberPeople ) {
    ElMessage.warning('请填写必填信息')
    return
  }

  if (isEditing.value) {
    const index = tableData.findIndex(item => item.id === formData.id)
    if (index !== -1){
      tableData[index] = {
        ...formData,
      }
    }
    // 编辑逻辑（如果有需要的话）
  } else {
    // 新增逻辑
    const newId = tableData.length > 0 ? Math.max(...tableData.map(item => item.id)) + 1 : 1
    const newItem = {
      id: newId,
      status: formData.status,
      post: formData.post,
      section: formData.section,
      requirement: formData.requirement,
      numberPeople: formData.numberPeople,
      candidate: formData.candidate,
      entry: formData.entry,
      time: formData.time || new Date().toISOString().split('T')[0]
    }
    tableData.push(newItem)
  }

  dialogVisible.value = false
  ElMessage.success(isEditing.value? '更新成功' :'保存成功')
}
const handleEdit = (row: RecruitmentItem) => {
  isEditing.value = true
  Object.assign(formData, {
    ...row,
    numberPeople: Number(row.numberPeople),
    candidate: Number(row.candidate),
    entry: Number(row.entry),
  })
  dialogVisible.value = true
}
const searchForm = reactive({
  post: '',
  section: '',
  status: '',
  time: ''
})
/*const filterTableData = computed(() => {
  return tableData.filter(item => {
    const postMatatch = !searchForm.post || item.post.includes(searchForm.post);
    const sectionMatch = !searchForm.section || item.section.includes(searchForm.section);
    const statusMatch = !searchForm.status || item.status.includes(searchForm.status);
    return postMatatch && sectionMatch && statusMatch;
  })
})*/
const handleSearch = () => {
  // 搜索逻辑（如果有需要的话）
// 重新计算 filterTableData 即可触发搜索
  // 无需额外操作，computed 会自动响应 searchForm 的变化
}
const resetSearch = () => {
  Object.assign(searchForm, {
    post: '',
    section: '',
    status: '',
    time: ''
  })
}
</script>

<!-- 招聘岗位 -->
<template>
    <div class="container">
        <!-- 使用 Element Plus 的卡片组件作为页面容器，设置阴影效果 -->
        <el-card shadow="always" class="main-card">
            <!-- 页面标题区域 -->
            <div class="header-section">
                <span class="page-title">招聘岗位</span>
            </div>
            <!-- 搜索与操作按钮区域 -->
            <div class="search-section">
                <!-- 岗位名称搜索输入框及搜索按钮 -->
                <div class="search-input-wrapper">
                    <el-input v-model="searchForm.post" placeholder="岗位名称"  class="mobile-full-width"/>
                  <el-select v-model="searchForm.section" placeholder="部门" class="mobile-full-width">
                    <el-option label="技术部" value="技术部"></el-option>
                    <el-option label="销售部" value="销售部"></el-option>
                    <el-option label="人力资源部" value="人力资源部"></el-option>
                    <el-option label="财务部" value="财务部"></el-option>
                  </el-select>
                    <el-date-picker
                      v-model="searchForm.time"
                      type="date"
                      placeholder="选择日期"
                      class="search-date-picker"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                    >
                    </el-date-picker>
                    <el-button type="primary" class="search-button action-button" @click="handleSearch">搜索</el-button>
                  <el-button @click="resetSearch" class="search-button">重置</el-button>
                </div>
                <!-- 批量操作按钮组：结束招聘、批量删除 -->
                <div class="action-buttons">
                    <el-button type="primary"  @click="handleAdd">新增</el-button>
                    <el-button type="info"  @click="handleEndRecruitment">结束招聘</el-button>
                    <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
                </div>
            </div>
            <!-- 表格展示区域 -->
            <div class="table-wrapper">
                <!-- 招聘信息表格，配置了居中对齐样式和边框 -->
                <el-table 
                    :data="paginatedData"
                    border
                    :header-cell-style="{ textAlign: 'center' }"
                    :cell-style="{ textAlign: 'center' }" 
                    class="recruit-table responsive-table"
                    ref="multipleTableRef"
                    @selection-change="handleSelectionChange"
                >
                  <!-- 复选框列 -->
                  <el-table-column type="selection" width="50" />
                    <!-- 序号列 -->
                    <el-table-column prop="id" label="序号" width="60"/>
                    <!-- 状态列 -->
                  <el-table-column prop="status" label="状态" width="80" >
                    <template #default="{ row }">
                      <span class="status-tag status-active">{{row.status}}</span>
                    </template>
                  </el-table-column>
                    <!-- 岗位名称列 -->
                    <el-table-column prop="post" label="岗位名称" min-width="120" />
                    <!-- 招聘部门列 -->
                    <el-table-column prop="section" label="招聘部门" min-width="100"/>
                    <!-- 所属招聘需求列 -->
                    <el-table-column prop="requirement" label="所属招聘需求" min-width="120" />
                    <!-- 需求人数列 -->
                    <el-table-column prop="numberPeople" label="需求人数" width="80" />
                    <!-- 候选人员数列 -->
                    <el-table-column prop="candidate" label="候选人员" width="80" />
                    <!-- 已入职人数列 -->
                    <el-table-column prop="entry" label="已入职" width="80" />
                    <!-- 发布时间列 -->
                    <el-table-column prop="time" label="发布时间" width="120" />
                    <!-- 操作列（固定在右侧） -->
                    <el-table-column label="操作" fixed="right" width="80">
                      <template #default="{ row }">
                        <el-button type="primary" size="small"  @click="handleEdit(row)">编辑</el-button>
                      </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页控件区域 -->
            <div class="pagination-wrapper">
                <!-- Element Plus 分页组件，支持上一页、数字页码、下一页功能 -->
                <el-pagination 
                    size="small" 
                    background
                    layout="total, sizes, prev, pager, next, junper"
                    :total="filterTableData.length"
                    :page-sizes="[10, 20, 50, 100]"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    class="mt-4" 
                />
            </div>
        </el-card>
      <!-- 编辑/新增招聘信息弹窗 -->
      <el-dialog v-model="dialogVisible" title="招聘信息" class="recruit-dialog" @close="resetForm">
        <el-form label-width="120px" class="recruit-form">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="12" :lg="12">
              <el-form-item label="岗位名称" required>
                <el-input v-model="formData.post" placeholder="请输入岗位名称" />
              </el-form-item>
              <el-form-item label="招聘部门" required>
                <el-select v-model="formData.section" placeholder="请输入招聘部门" style="width: 100%">
                  <el-option label="技术部" value="技术部" />
                  <el-option label="财务部" value="财务部" />
                  <el-option label="销售部" value="销售部" />
                  <el-option label="行政部" value="行政部" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12">
              <el-form-item label="需求人数" required>
                <el-input-number v-model="formData.numberPeople" placeholder="请输入需求人数" :min="0"  style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12">
              <el-form-item label="候选人员数" required>
                <el-input-number v-model="formData.candidate" placeholder="请输入候选人员数" :min="0"  style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12">
              <el-form-item label="已入职人数" required>
                <el-input-number v-model="formData.entry" placeholder="请输入已入职人数" :min="0" style="width: 100%;"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="12" :lg="12">
              <el-form-item label="状态" required>
                <el-select v-model="formData.status" placeholder="请选择状态">
                  <el-option label="待发布" value="待发布" />
                  <el-option label="进行中" value="进行中" />
                  <el-option label="已结束" value="已结束" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12">
              <el-form-item label="发布时间" required>
                <el-date-picker v-model="formData.time" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="所属需求" required>
                <el-input v-model="formData.requirement" type="textarea" placeholder="请输入所属需求" :autosize="{ minRows:2, maxRows:4}"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 弹窗底部按钮栏 -->
        <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isEditing" @click="resetForm">重置</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
        </template>
      </el-dialog>
    </div>
</template>
  


<style>
.header-section{
  margin-bottom: 20px;
}
.page-title{
  font-size: 20px;
  font-weight: bold;
}
.search-section{
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
}
.search-input-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
  flex: 1;
}

.mobile-full-width,
.search-date-picker {
  flex: 1;
  width: 150px;
}

.search-button {
  white-space: nowrap;
}
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input-wrapper {
    flex-direction: column;
  }

  .mobile-full-width,
  .search-date-picker {
    min-width: auto;
  }
}
</style>
